<template>
  <div class="station-dashboard">
    <!-- 站点信息卡片 -->
    <el-card class="station-info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>{{ stationInfo.name }}</h3>
          <el-tag :type="getStationStatusType(stationInfo.status)">
            {{ getStationStatusText(stationInfo.status) }}
          </el-tag>
        </div>
      </template>
      <div class="station-details">
        <div class="detail-row">
          <span class="label">地址:</span>
          <span class="value">{{ stationInfo.address }}</span>
        </div>
        <div class="detail-row">
          <span class="label">联系电话:</span>
          <span class="value">{{ stationInfo.contactPhone }}</span>
        </div>
        <div class="detail-row">
          <span class="label">站点容量:</span>
          <span class="value">{{ stationInfo.capacity }}kg</span>
        </div>
        <div class="detail-row">
          <span class="label">当前负载:</span>
          <span class="value">{{ stationInfo.currentLoad }}kg</span>
          <el-progress 
            :percentage="loadPercentage" 
            :stroke-width="8"
            :color="getLoadColor(loadPercentage)"
            class="load-progress"
          />
        </div>
      </div>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stats-grid">
      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon pending">
            <el-icon size="28"><Clock /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ pendingOrders }}</h3>
            <p>待处理订单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon processing">
            <el-icon size="28"><Loading /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ processingOrders }}</h3>
            <p>处理中订单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon completed">
            <el-icon size="28"><Check /></el-icon>
          </div>
          <div class="stats-info">
            <h3>{{ completedOrders }}</h3>
            <p>今日完成订单</p>
          </div>
        </div>
      </el-card>

      <el-card class="stats-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-icon revenue">
            <el-icon size="28"><Money /></el-icon>
          </div>
          <div class="stats-info">
            <h3>¥{{ todayRevenue }}</h3>
            <p>今日收入</p>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 总计统计 -->
    <el-card class="total-stats-card" shadow="never" style="margin-top: 16px;">
      <div class="stats-summary">
        <div class="summary-item">
          <span class="summary-label">订单总数</span>
          <span class="summary-value">{{ totalOrders }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">历史总收入</span>
          <span class="summary-value">¥{{ totalRevenue }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">历史完成订单</span>
          <span class="summary-value">{{ totalCompleted }}</span>
        </div>
      </div>
    </el-card>

    <!-- 订单处理和库存状态 -->
    <div class="content-section">
      <el-row :gutter="24">
        <el-col :span="14">
          <el-card title="待处理订单" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>待处理订单</span>
                <el-button type="primary" size="small" @click="$router.push('/station/orders')">
                  查看全部
                </el-button>
              </div>
            </template>
            <el-table 
              :data="pendingOrderList" 
              style="width: 100%" 
              v-loading="loading"
              :empty-text="loading ? '加载中...' : '暂无待处理订单'"
              class="order-table"
            >
              <el-table-column prop="orderNo" label="订单号" width="150" />
              <el-table-column label="客户" width="80">
                <template #default="scope">
                  <span>{{ scope.row.customerName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="pickupAddress" label="取货地址" show-overflow-tooltip />
              <el-table-column label="预约时间" width="150">
                <template #default="scope">
                  <span>{{ scope.row.pickupTime || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="金额" width="100">
                <template #default="scope">
                  <span>¥{{ scope.row.totalAmount ? scope.row.totalAmount.toFixed(2) : '0.00' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="confirmOrder(scope.row)"
                  >
                    确认
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="10">
          <el-card title="库存状态" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>库存状态</span>
                <el-button type="primary" size="small" @click="$router.push('/station/inventory')">
                  管理库存
                </el-button>
              </div>
            </template>
            <div class="inventory-list" v-loading="loading">
              <div 
                v-for="item in inventoryStatus" 
                :key="item.id" 
                class="inventory-item"
              >
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-quantity">
                    库存: {{ item.quantity }}{{ item.unit }}
                  </div>
                </div>
                <div class="item-status">
                  <el-tag 
                    :type="getInventoryStatusType(item.status)" 
                    size="small"
                  >
                    {{ getInventoryStatusText(item.status) }}
                  </el-tag>
                </div>
              </div>
              <div v-if="!loading && inventoryStatus.length === 0" class="empty-inventory">
                <el-empty description="暂无库存数据" :image-size="60" />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <el-card title="快捷操作" shadow="hover">
        <div class="action-buttons">
          <el-button 
            type="primary" 
            icon="Document" 
            size="large"
            @click="$router.push('/station/orders')"
          >
            订单处理
          </el-button>
          <el-button 
            type="success" 
            icon="Box" 
            size="large"
            @click="$router.push('/station/inventory')"
          >
            库存管理
          </el-button>
          <el-button 
            type="warning" 
            icon="Setting" 
            size="large"
            @click="$router.push('/station/info')"
          >
            站点设置
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { stationsAPI, ordersAPI, itemsAPI } from '@/api'
import {
  Clock,
  Loading,
  Check,
  Money
} from '@element-plus/icons-vue'

// 组件名称
defineOptions({
  name: 'StationDashboard'
})

const store = useStore()
const loading = ref(false)

// 站点信息
const stationInfo = ref({
  id: null,
  name: '',
  address: '',
  contactPhone: '',
  capacity: 0,
  currentLoad: 0,
  status: 'active'
})

// 统计数据
const pendingOrders = ref(0)
const processingOrders = ref(0)
const completedOrders = ref(0)
const todayRevenue = ref('0')
const totalOrders = ref(0)
const totalCompleted = ref(0)
const totalRevenue = ref('0')

// 计算属性
const loadPercentage = computed(() => {
  return Math.round((stationInfo.value.currentLoad / stationInfo.value.capacity) * 100)
})

// 待处理订单列表
const pendingOrderList = ref([])

// 库存状态
const inventoryStatus = ref([])

// 状态映射函数
const getStationStatusType = (status) => {
  const types = {
    active: 'success',
    busy: 'warning',
    closed: 'danger'
  }
  return types[status] || 'info'
}

const getStationStatusText = (status) => {
  const texts = {
    active: '正常运营',
    busy: '繁忙',
    closed: '关闭'
  }
  return texts[status] || '未知'
}

const getLoadColor = (percentage) => {
  if (percentage < 50) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

const getInventoryStatusType = (status) => {
  const types = {
    normal: 'success',
    low: 'warning',
    empty: 'danger'
  }
  return types[status] || 'info'
}

const getInventoryStatusText = (status) => {
  const texts = {
    normal: '正常',
    low: '不足',
    empty: '缺货'
  }
  return texts[status] || '未知'
}

// 获取站点信息
const fetchStationInfo = async () => {
  try {
    const user = store.state.user
    
    if (!user || !user.id) {
      const userId = localStorage.getItem('userId')
      
      if (!userId) {
        ElMessage.error('用户信息不完整，请重新登录')
        return
      }
      
      // 使用 localStorage 中的用户ID
      const managerId = parseInt(userId)
      
      // 获取当前用户管理的站点
      const response = await stationsAPI.getStations({ 
        managerId: managerId,
        page: 1,
        pageSize: 10
      })
      
      // 兼容不同的返回格式
      const stationList = response.list || response.data || response || []
      
      if (stationList.length > 0) {
        const station = stationList[0]
        stationInfo.value = station
        store.commit('SET_CURRENT_STATION', station)
        
        // 获取该站点的订单数据
        await fetchOrdersData(station.id)
      } else {
        ElMessage.warning('您还没有分配管理的站点，请联系管理员')
      }
      return
    }
    
    // 获取当前用户管理的站点
    const response = await stationsAPI.getStations({ 
      managerId: user.id,
      page: 1,
      pageSize: 10
    })
    
    // 兼容不同的返回格式
    const stationList = response.list || response.data || response || []
    
    if (stationList.length > 0) {
      const station = stationList[0]
      stationInfo.value = station
      store.commit('SET_CURRENT_STATION', station)
      
      // 获取该站点的订单数据
      await fetchOrdersData(station.id)
    } else {
      ElMessage.warning('您还没有分配管理的站点，请联系管理员')
    }
  } catch (error) {
    console.error('获取站点信息失败:', error)
    ElMessage.error('获取站点信息失败: ' + (error.message || '未知错误'))
  }
}

// 获取订单数据
const fetchOrdersData = async (stationId) => {
  try {
    // 使用按站点查询的API
    const response = await ordersAPI.getStationOrders(stationId, {
      page: 1,
      pageSize: 100
    })
    
    // 兼容不同的返回格式
    const orders = response.list || response.data || response || []
    
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    // 统计各状态订单数量
    const pending = orders.filter(o => o.status === 'pending')
    const processing = orders.filter(o => o.status === 'confirmed' || o.status === 'in_progress')
    
    pendingOrders.value = pending.length
    processingOrders.value = processing.length
    
    // 今日完成订单
    const todayCompleted = orders.filter(o => {
      if (o.status !== 'completed') return false
      const orderDate = new Date(o.updatedAt)
      return orderDate >= today
    })
    completedOrders.value = todayCompleted.length
    
    // 今日收入
    const todayIncome = todayCompleted.reduce((sum, order) => {
      return sum + (Number(order.totalAmount) || 0)
    }, 0)
    todayRevenue.value = todayIncome.toFixed(2)
    
    // 总计统计
    totalOrders.value = orders.length
    
    const allCompleted = orders.filter(o => o.status === 'completed')
    totalCompleted.value = allCompleted.length
    
    const allIncome = allCompleted.reduce((sum, order) => {
      return sum + (Number(order.totalAmount) || 0)
    }, 0)
    totalRevenue.value = allIncome.toFixed(2)
    
    // 待处理订单列表（只显示前3条）
    pendingOrderList.value = pending
      .slice(0, 3)
      .map(order => ({
        ...order,
        pickupTime: order.pickupTime ? formatDateTime(order.pickupTime) : '-'
      }))
  } catch (error) {
    console.error('获取订单数据失败:', error)
    ElMessage.error('获取订单数据失败: ' + (error.message || '未知错误'))
  }
}

// 获取库存状态
const fetchInventoryStatus = async () => {
  try {
    const response = await itemsAPI.getItems({
      page: 1,
      pageSize: 5
    })
    
    // 兼容不同的返回格式
    const items = response.list || response.data || response || []
    inventoryStatus.value = items.map(item => {
      // 根据实际情况判断库存状态（这里使用随机值模拟）
      const quantity = Math.floor(Math.random() * 500)
      let status = 'normal'
      if (quantity < 50) status = 'low'
      else if (quantity === 0) status = 'empty'
      
      return {
        id: item.id,
        name: item.name,
        quantity: quantity,
        unit: item.unit,
        status: status
      }
    })
  } catch (error) {
    console.error('获取库存状态失败:', error)
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 确认订单
const confirmOrder = async (order) => {
  try {
    await ordersAPI.updateOrderStatus(order.id, 'confirmed')
    ElMessage.success(`订单 ${order.orderNo} 确认成功`)
    
    // 重新获取数据
    await fetchOrdersData(stationInfo.value.id)
  } catch (error) {
    console.error('确认订单失败:', error)
    ElMessage.error('确认订单失败')
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    await fetchStationInfo()
    await fetchInventoryStatus()
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  initData()
})
</script>

<style scoped>
.station-dashboard {
  padding: 0;
}

.station-info-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.station-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.detail-row .label {
  font-weight: 500;
  color: #666;
  width: 80px;
}

.detail-row .value {
  color: #333;
  flex: 1;
}

.load-progress {
  flex: 1;
  max-width: 200px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 12px;
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stats-icon.pending {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.stats-icon.processing {
  background: linear-gradient(135deg, #409EFF 0%, #66B2FF 100%);
}

.stats-icon.completed {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.stats-icon.revenue {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
}

.stats-info h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stats-info p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.stats-change {
  font-size: 12px;
  color: #999;
}

.stats-change.positive {
  color: #67C23A;
}

.content-section {
  margin-bottom: 24px;
}

.order-table :deep(.el-table__body) {
  font-size: 14px;
}

.order-table :deep(.el-table__header) {
  font-size: 14px;
}

.inventory-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.inventory-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  font-size: 14px;
}

.item-quantity {
  font-size: 12px;
  color: #666;
}

.empty-inventory {
  padding: 20px;
  text-align: center;
}

.quick-actions {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  flex: 1;
  min-width: 120px;
}

/* 总计统计卡片样式 */
.total-stats-card {
  border-radius: 8px;
}

.total-stats-card :deep(.el-card__body) {
  padding: 16px 24px;
}

.stats-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  gap: 32px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.summary-value {
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-summary {
    flex-direction: column;
    gap: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
